// src/logical/user/user.service.ts
import { Injectable } from '@nestjs/common'
// typeorm
import { makeSalt, encryptPassword } from '../../utils/cryptogram' // 引入加密函数import { User } from './user.entity';
import { User } from './entity/user.entity'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { RegisterInfoDTO, LoginDTO, RegisterDTO } from './user.dto'
@Injectable()
export class UserService {
    // typeorm
    constructor(
        @InjectRepository(User)
        private usersRepository: Repository<User>
    ) {}
    async findAll(): Promise<User[]> {
        return this.usersRepository.find()
    }
    /**
     * 查询是否有该用户
     * @param username 用户名
     */
    async findOne(username: string): Promise<any | undefined> {
        return this.usersRepository.findOne({ user_name: username })
    }
    /**
     * 注册
     * @param requestBody 请求体
     */
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    async register(requestBody: any): Promise<any> {
        const { user_name, password, repassword, mobile } = requestBody
        if (password !== repassword) {
            return {
                code: 400,
                msg: '两次密码输入不一致'
            }
        }
        const user = await this.findOne(user_name)
        if (user) {
            return {
                code: 400,
                msg: '用户已存在'
            }
        }
        const salt = makeSalt() // 制作密码盐
        const hashPwd = encryptPassword(password, salt) // 加密密码

        const userInfo = new User()
        userInfo.user_name = user_name
        userInfo.password = hashPwd
        userInfo.passwd_salt = salt
        userInfo.mobile = mobile
        userInfo.user_status = 0
        userInfo.create_by = new Date().getTime()
        try {
            await this.usersRepository.save(userInfo)
        } catch (error) {
            return {
                code: 500,
                msg: error
            }
        }
        return {
            code: 200,
            msg: '注册成功'
        }
    }
    /**
     * 删除id
     * @param id 用户id
     */
    async remove(id: string): Promise<void> {
        await this.usersRepository.delete(id)
    }
    /**
     * 创建用户
     * @param
     */
    create(registerInfoDTO: RegisterInfoDTO): Promise<User> {
        const salt = makeSalt() // 制作密码盐
        const hashPwd = encryptPassword(registerInfoDTO.password, salt) // 加密密码
        const userInfo = new User()
        userInfo.user_name = registerInfoDTO.user_name
        userInfo.password = hashPwd
        userInfo.passwd_salt = salt
        userInfo.mobile = registerInfoDTO.mobile

        return this.usersRepository.save(userInfo)
    }
}
